mod ui;
mod gitee_api;
mod config;
mod views;

use config::Config;
use std::io;
use crossterm::{
    event::{self, Event, KeyCode},
    terminal::{disable_raw_mode, enable_raw_mode},
};
use ratatui::{backend::CrosstermBackend, Terminal};
use views::pr_form::PrForm;
use std::time::Duration;
use std::io::Write;


fn main() -> Result<(), io::Error> {
    config::Config::ensure_exists().expect("⚠️ 初始化配置失败");
    config::clear_screen();
    enable_raw_mode()?;

    let mut stdout = io::stdout();
    let backend = CrosstermBackend::new(&mut stdout);
    let mut terminal = Terminal::new(backend)?;

    loop {
        ui::draw_main_menu(&mut terminal)?;

        if event::poll(Duration::from_millis(500))? {
            if let Event::Key(key) = event::read()? {
                match key.code {
                    KeyCode::Char('1') => {
                        create_pr_flow();
                    }
                    KeyCode::Char('2') => comment_pr_flow(),
                    KeyCode::Char('q') => {
                        break;
                    }
                    _ => {}
                }
            }
        }
    }

    disable_raw_mode()?;
    config::clear_screen();
    Ok(())
}

fn create_pr_flow() {
    let config = match Config::load() {
        Ok(cfg) => cfg,
        Err(e) => {
            eprintln!("❌ 配置加载失败: {}", e);
            return;
        }
    };

    // 启动自己的 TUI terminal
    let backend = CrosstermBackend::new(std::io::stdout());
    let mut terminal = Terminal::new(backend).unwrap();

    let mut form = PrForm::new();

    // 表单输入循环
    loop {
        form.render(&mut terminal).unwrap();

        if event::poll(std::time::Duration::from_millis(100)).unwrap() {
            let evt = event::read().unwrap();
            if form.handle_event(evt) {
                break; // Esc 退出表单
            }
        }
    }

    // ✅ 正确退出 raw mode 并清理 terminal 状态
    disable_raw_mode().ok();
    terminal.show_cursor().ok();
    terminal.clear().ok();

    // 执行 PR 提交
    let title = form.title.lines().join("\n");
    let head = form.head.lines().join("\n");
    let base = form.base.lines().join("\n");
    let body = form.body.lines().join("\n");

    println!("📤 正在创建 PR...");
    match gitee_api::create_pr(
        &config.owner,
        &config.repo,
        &config.access_token,
        &title,
        &head,
        &base,
        &body,
    ) {
        Ok(pr) => {
            println!("✅ PR #{} 创建成功！", pr.number);
            println!("🔗 链接: {}", pr.url);
        }
        Err(e) => {
            eprintln!("❌ PR 创建失败: {}", e);
        }
    }

    println!("\n按回车返回主菜单...");
    let _ = std::io::stdin().read_line(&mut String::new());

    // ✅ 重新进入 raw mode 给主菜单用
    enable_raw_mode().ok();
}

fn comment_pr_flow() {
    let config = match Config::load() {
        Ok(cfg) => cfg,
        Err(e) => {
            eprintln!("❌ 配置加载失败: {}", e);
            return;
        }
    };

    disable_raw_mode().ok();
    config::clear_screen();

    // 先输入 PR 编号（暂时用 CLI）
    let mut input = String::new();
    print!("💬 请输入 PR 编号: ");
    std::io::stdout().flush().unwrap();
    std::io::stdin().read_line(&mut input).unwrap();
    let pr_number: u64 = match input.trim().parse() {
        Ok(n) => n,
        Err(_) => {
            eprintln!("❌ 无效的 PR 编号");
            return;
        }
    };

    enable_raw_mode().ok();
    config::clear_screen();

    // TUI 输入评论
    let backend = CrosstermBackend::new(std::io::stdout());
    let mut terminal = Terminal::new(backend).unwrap();
    let mut form = views::comment_form::CommentForm::new();

    loop {
        form.render(&mut terminal).unwrap();

        if event::poll(Duration::from_millis(100)).unwrap() {
            let evt = event::read().unwrap();
            if form.handle_event(evt) {
                break;
            }
        }
    }

    disable_raw_mode().ok();
    terminal.show_cursor().ok();
    terminal.clear().ok();

    let comment_text = form.get_comment();

    if comment_text.trim().is_empty() {
        println!("⚠️ 评论为空，已取消发送");
    } else {
        match gitee_api::comment_pr(
            &config.owner,
            &config.repo,
            pr_number,
            &config.access_token,
            &comment_text,
        ) {
            Ok(_) => println!("✅ 评论发送成功！"),
            Err(e) => eprintln!("{}", e),
        }
    }

    println!("\n按回车退出程序...");
std::io::stdout().flush().unwrap();
use crossterm::event::{read, Event, KeyCode};

loop {
    if let Event::Key(key_event) = read().unwrap() {
        if key_event.code == KeyCode::Enter {
            std::process::exit(0);
        }
    }
}

    enable_raw_mode().ok();
}
